package com.tv.enoguia;

import java.util.ArrayList;
import java.util.HashMap;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.tv.enoguia.bean.Celler;
import com.tv.enoguia.database.MySQLiteHelper;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class LocationActivity extends Activity implements OnClickListener,
		OnTouchListener, LocationListener {

	TextView title;
	// map
	private GoogleMap googleMap;
	Location location;
	double mLatitude;
	double mLongitude;

	private ArrayList<Celler> mMyMarkersArray;
	private HashMap<Marker, Celler> mMarkersHashMap;
	ArrayList<Celler> cellers;
	MySQLiteHelper db;

	DisplayImageOptions options = new DisplayImageOptions.Builder()
	.cacheInMemory(false).cacheOnDisc(true)
	.bitmapConfig(Config.RGB_565).build();
	
	Runnable r = new Runnable() {

		@Override
		public void run() {
			cellers = db.getAllCelers();
			addMarker();
		}
	};

	Handler mHandler = new Handler();
	AddmakerAsyn addmakerAsyn;
	
	private Marker mSelectedMarker;
    private boolean mRefreshingInfoWindow;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_location);

		title = (TextView) findViewById(R.id.title);

		db = new MySQLiteHelper(this);
		
		addmakerAsyn = new AddmakerAsyn();
		

		mMarkersHashMap = new HashMap<Marker, Celler>();

		// plotMarkers(mMyMarkersArray);

		// Getting status
		int status = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(getBaseContext());
		// Showing status
		if (status == ConnectionResult.SUCCESS) {
			setUpMap();
			focusLocation();
//			mHandler.postDelayed(r, 3000);
		} else {
			Toast.makeText(LocationActivity.this,
					"Google Play Services are not available",
					Toast.LENGTH_SHORT).show();
			int requestCode = 10;
			Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
					requestCode);
			dialog.show();
		}
		
		addmakerAsyn.execute("");
		init();
	}

	void init() {
		title.setText(getString(R.string.txt_map));
	}

	
	
	@Override
	protected void onPause() {
		super.onPause();
		addmakerAsyn.cancel(true);
	}

	@SuppressLint("NewApi")
	private void setUpMap() {
		// Do a null check to confirm that we have not already instantiated the
		// map.
		if (googleMap == null) {
			// Try to obtain the map from the SupportMapFragment.
			googleMap = ((MapFragment) getFragmentManager().findFragmentById(
					R.id.map)).getMap();
			// googleMap = ((SupportMapFragment)
			// getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

			// Check if we were successful in obtaining the map.

			// Enabling MyLocation in Google Map
			googleMap.setMyLocationEnabled(true);
			googleMap.getUiSettings().setMyLocationButtonEnabled(true);

			/*
			 * // Creating an instance of MarkerOptions MarkerOptions
			 * markerOptions = new MarkerOptions();
			 * 
			 * // Setting position for the marker markerOptions.position(new
			 * LatLng(mLatitude, mLongitude));
			 * 
			 * // Setting custom icon for the marker
			 * markerOptions.icon(BitmapDescriptorFactory
			 * .fromResource(R.drawable.my_location));
			 * 
			 * // Adding the marker to the map
			 * googleMap.addMarker(markerOptions);
			 * 
			 * googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {
			 * 
			 * @Override public boolean onMarkerClick(Marker marker) { return
			 * false; } });
			 */
			// Getting LocationManager object from System Service
			// LOCATION_SERVICE
			LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

			// Creating a criteria object to retrieve provider
			Criteria criteria = new Criteria();

			// Getting the name of the best provider
			String provider = locationManager.getBestProvider(criteria, true);

			// Getting Current Location From GPS

			location = locationManager.getLastKnownLocation(provider);

			if (location != null) {
				onLocationChanged(location);
			}

			locationManager.requestLocationUpdates(provider, 60000, 0,
					new android.location.LocationListener() {

						@Override
						public void onStatusChanged(String provider,
								int status, Bundle extras) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onProviderEnabled(String provider) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onProviderDisabled(String provider) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onLocationChanged(Location location) {
						}
					});
		}

		googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
			
			@Override
			public void onInfoWindowClick(Marker marker) {
				Celler celler = mMarkersHashMap.get(marker);
				Intent t = new Intent(LocationActivity.this, DetailBussinessActivity.class);
				t.putExtra("id", celler.getId());
				startActivity(t);
			}
		});
	}

	void focusLocation() {
		try {
			// spain
			mLatitude = 41.32371706918535;
			mLongitude = 0.8771441019912345;
			LatLng latLng = new LatLng(mLatitude, mLongitude);
			googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
			googleMap.animateCamera(CameraUpdateFactory.zoomTo(8));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onLocationChanged(Location arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub

	}

	void addMarker() {
		mMyMarkersArray = new ArrayList<Celler>();
		for (int i = 0; i < cellers.size(); i++) {
			mMyMarkersArray.add(cellers.get(i));
		}
		
		plotMarkers(mMyMarkersArray);
	}

	private void plotMarkers(ArrayList<Celler> markers) {
		if (markers.size() > 0) {
			for (Celler celler : markers) {

				// Create user marker with custom icon and other options
				MarkerOptions markerOption = new MarkerOptions()
						.position(new LatLng(
								Double.parseDouble(celler.getLat()), Double
										.parseDouble(celler.getLon())));
				markerOption.icon(BitmapDescriptorFactory
						.fromResource(R.drawable.pin_celler));

				Marker currentMarker = googleMap.addMarker(markerOption);
				mMarkersHashMap.put(currentMarker, celler);
				
				googleMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());

			}
		}
		addmakerAsyn.cancel(true);
	}
	
	public class AddmakerAsyn extends AsyncTask<String, String, String>{

		@Override
		protected String doInBackground(String... arg0) {
			cellers = db.getAllCelersMap();
			return "";
		}


		@Override
		protected void onPostExecute(String result) {
			addMarker(); 
		}
	}
	
	 private void refreshInfoWindow() {
	        if (mSelectedMarker == null) {
	            return;
	        }
	        mRefreshingInfoWindow = true;
	        mSelectedMarker.showInfoWindow();
	        mRefreshingInfoWindow = false;
	    }
	
	public class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {
		public MarkerInfoWindowAdapter() {
		}

		@Override
		public View getInfoWindow(final Marker marker) {
			return null;
		}

		View v;
		@Override
		public View getInfoContents(final Marker marker) {
			if (!mRefreshingInfoWindow) {
                mSelectedMarker = marker;
                v = getLayoutInflater().inflate(R.layout.maker_info_i, null, false);
                
                Celler celler = mMarkersHashMap.get(marker);
                
				TextView cellarName = (TextView) v.findViewById(R.id.txt_name_bussiness);
				TextView towName = (TextView) v.findViewById(R.id.txt_town);
				final ImageView image = (ImageView) v.findViewById(R.id.img_bus);
				ImageLoader.getInstance().displayImage("http://enoguia.cat/img/fotos/"+celler.getPhoto(),
						image, options, new SimpleImageLoadingListener() {
	
							@Override
							public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
								super.onLoadingComplete(imageUri, view, loadedImage);
								Log.i("DATA", "---------------");
								//getInfoContents(marker);
								refreshInfoWindow();
							}
						});
				
				cellarName.setText(celler.getCellarName());
				towName.setText(celler.getTowName());
			}
			return v;
		}

	}

}
